package com.example.mycamerademo.utils

import android.graphics.*
import android.hardware.Camera
import com.cbly.jpegturbo.TJ
import com.cbly.jpegturbo.TurboJpegLib
import java.io.ByteArrayOutputStream
import java.util.*

/**
 * @author tgw
 * @date 2021/12/16
 * @describe
 */
object ImageDataUtils {

    fun bytesToBitmap(b: ByteArray, width: Int,height: Int): Bitmap? {
        return if (b.isNotEmpty()) {
            //处理data
            val newOpts = BitmapFactory.Options()
            newOpts.inJustDecodeBounds = true
            val yuVImage = YuvImage(
                b,
                ImageFormat.YUY2,
                width,
               height,
                null)
            val bOs = ByteArrayOutputStream()
            yuVImage.compressToJpeg(
                Rect(0,
                0,
                width,
                height), 100, bOs) // 80--JPG图片的质量[0-100],100最高
            val rawImage = bOs.toByteArray()
            //将rawImage转换成bitmap
            val options = BitmapFactory.Options()
            options.inPreferredConfig = Bitmap.Config.RGB_565
            BitmapFactory.decodeByteArray(rawImage, 0, rawImage.size, options)
        } else {
            null
        }
    }



    //参考  https://blog.csdn.net/q979713444/article/details/80446404
    /**有问题*/
    fun onPreviewFrame(nv21: ByteArray,width: Int,height: Int) {
        var mTempI420: ByteArray? = null
        var mMaxJpeg: ByteArray? = null
        if (mTempI420 == null) {
            mTempI420 = ByteArray(nv21.size)
        }
        if (mMaxJpeg == null) {
            mMaxJpeg = ByteArray(nv21.size * 2)
        }
        val compressSize = TurboJpegLib.yuv2jpeg(
            nv21, mTempI420, width, height,
            TJ.SAMP_420, nv21, 70, TJ.FLAG_BOTTOMUP
        )

        // 下方返回的结果就是最终把nv21帧数据压缩后的jpeg的二进制字节
        val jpegDataOut: ByteArray = Arrays.copyOfRange(nv21, 0, compressSize)
        val rawImage = nv21
        //将rawImage转换成bitmap
        val options = BitmapFactory.Options()
        BitmapFactory.decodeByteArray(jpegDataOut, 0, rawImage.size, options)
    }
}